package cn.yunyichina.provider.guide.service.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.yunyichina.provider.guide.GuideConstants;
import cn.yunyichina.provider.guide.dao.InstanceDao;
import cn.yunyichina.provider.guide.dao.InstanceNodeDao;
import cn.yunyichina.provider.guide.dao.InstanceRelationDao;
import cn.yunyichina.provider.guide.dao.RegisterStatusDao;
import cn.yunyichina.provider.guide.dao.TemplateDao;
import cn.yunyichina.provider.guide.entity.InstanceNode;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;

/**
 * 导医,定时扫描代缴费状态的导医流程，以便生成待缴后续的订单节点
 * @author adriftor
 *
 */
@Service("guidepayingServiceImpl")
public class GuidePayingServiceImpl  {
	
	private static final Logger logger = LoggerFactory.getLogger(GuidePayingServiceImpl.class);
	
	
	
	@Resource
	private InstanceDao instanceDao;
	
	@Resource
	private TemplateDao templateDao;
	
	@Resource
	private InstanceNodeDao instanceNodeDao;
	
	@Resource
	private InstanceRelationDao instanceRelationDao;
	
	@Resource
	private GuideTemplateServiceImpl guideTemplateService;
	
	@Resource
	private GuideInstanceServiceImpl guideInstanceService;
	
	
	private static Boolean isRunning = false;
	
	@Resource
	private GuideSyncStopServiceImpl guideSyncEndService;

	
	@Resource
	private RegisterStatusDao registerStatusDao;
	
	/**
	 * 定时扫描代缴费状态的导医流程，以便生成待缴后续的订单节点
	 * @param strJson
	 * @param instanceId
	 */
	public void doSync() {
		
		if (isRunning) {
			logger.info("定时生成订单节点正在运行,禁止重入");
			return;
		}
		
		isRunning = true;
		
		Long start = System.currentTimeMillis();
		try {
			
			logger.info("paying--start");
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DATE, -1);
			
			Calendar cNode = Calendar.getInstance();
			cNode.add(Calendar.HOUR_OF_DAY, -12);

			List<InstanceNode> listInstanceNode = instanceNodeDao.listPayingInstance(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()),GuideConstants.YYYYMMDDHHMMSS.format(cNode.getTime()));
			logger.info("listInstance-size="+listInstanceNode.size());
			
			for (InstanceNode instanceNode : listInstanceNode) {
				
				guideInstanceService.genOrderNode(instanceNode);
				
			}//for
					
			logger.info("paying--ok");
			
			logger.info("GuidePayingServiceImpl耗时： "+(System.currentTimeMillis()-start)+"毫秒");
			
			//调用时间控制
			Thread.sleep(1000*3*60);
		}
		catch (Exception ex) {
			logger.error(ErrorCodeDefine.GUIDE_COMMON,"定时生成订单节点正在运行异常",ex);
		}
		finally {
			isRunning = false;
		}
		
	}

}
